var util = require('../../utils/util.js')
var app = getApp();

const db = wx.cloud.database({
  throwOnNotFound: false
})
const _ = db.command
Page({
  data: {
    id: 0,
    re: false,
    time: util.formatDate(new Date()),
    detail: [],
    userInfo: [],
    num: 0,
    phone: "",
    confirm: false
  },


  onLoad: function (options) {
    let id = options.id;
    var time = util.formatDate(new Date());
    var phone = "";
    console.log("time is ", time)
    this.setData({
      id: id,
      time: time
    });
    this.getDetail();

    //判断用户是否授权登录
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          console.log("用户已授权")
        } else {
          console.log("用户未授权")
          wx.redirectTo({
            url: '../mine/login'
          });
        }
      }
    });

    //判断用户是否注册，返回re值true/false
    wx.cloud.callFunction({ //调用云函数获取openid
      name: "getOpenId",
      complete: res => {
        db.collection("userInfo").where({
          _openid: res.result.openid //进行筛选
        }).get({
          success: res => {
            console.log("查找用户注册信息成功", res)
            if (res.data.length === 1) {
              this.setData({
                  re: true,
                  userInfo: res.data[0]
                }),
                console.log("用户已注册", this.data.re)
            } else {
              this.setData({
                  re: false
                }),
                console.log("用户未注册", this.data.re)

            }
          },
          fail: res => {
            console.log("查找用户注册信息失败", res)
          }
        })
      }
    });


  },

  showLocation(e) {
    let location = this.data.detail.location;
    if (location && location.latitude && location.longitude) {
      location.scale = 18;
      wx.openLocation(location);
    }
  },
  //访问网络,请求数据  
  getDetail() {
    var that = this;
    let id = this.data.id;
    if (!id) {
      wx.showToast({
        icon: "none",
        title: '参数错误',
        duration: 3000,
      })
      return;
    }
    wx.showLoading({
      title: '数据加载中',
      mask: true,
    })
    wx.cloud.callFunction({
      name: 'queryDetail',
      data: {
        id: this.data.id
      },
      success: res => {
        console.log('[云函数] [queryDetail 调用成功] : ', res.result)
        if (res.result) {
          that.setData({
            detail: res.result.data,
            num: res.result.data.num,
            phone: res.result.data.phone
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.result.msg,
            duration: 2000,
          })
        }
      },
      fail: err => {
        console.error('[云函数] [queryDetail] 调用失败', err)
        wx.showToast({
          icon: "none",
          title: "获取数据失败",
          duration: 2000,
        })
      },
      complete: () => {
        wx.hideLoading();
      }
    })
  },

  //拉起电话通信
  callPhone: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.phone //仅为示例，并非真实的电话号码
    })
    console.log("打电话", this.data.phone)
  },
  //报名按钮，先判断是否注册，未注册弹框注册提示，已注册弹框报名确认，再判断剩余名额，num-1,
  toConfirm: function () {
    let that = this;
    let id = this.data.id;
    let re = this.data.re;
    let confirm = this.data.confirm;
    console.log("re:", re)
    console.log("未报名:", confirm)

    if (confirm == true) {
      wx.showToast({
        title: '您已经完成报名！',
        icon: '',
        duration: 1000
      })
      return;
    }
    if (re == false) {
      console.log("用户未注册", this.data.re)
      this.setData({
          re: false
        }),

        wx.showModal({
          title: '提示',
          content: '请先注册成为志愿者！',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定'),
                wx.navigateTo({
                  url: '../register/newuser',
                })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

    } else {

      db.collection('taskList').doc(id).field({
        num: true
      }).get({
        success: (res) => {
          console.log(res)
          if (res.data.num > 0) {
            console.log("num>0，允许报名", res.data.num),

              console.log("弹出确认报名框"),
              wx.showModal({
                title: '报名确认',
                content: '确认要报名吗？',
                success: (res) => {
                  if (res.confirm) {
                    console.log('点击确认回调')
                    wx.showToast({
                        title: '报名成功！',
                        icon: '', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                        duration: 2000, //停留时间
                      }),
                      //taskList数据库更新num-1
                      db.collection('taskList').doc(id).update({
                        data: {
                          num: _.inc(-1)
                        },
                        success: (res) => {

                          console.log("报名成功，num-1", res)

                          db.collection('taskList').doc(id).field({
                            num: true
                          }).get({
                            success: (res) => {
                              console.log(res.data.num)

                              this.setData({
                                num: this.data.num - 1

                              })
                            }
                          })

                        },
                        fail: function (res) {
                          console.log("更新num失败", res)

                        }
                      }),

                      //查找用户的_id，通过id更新待审核志愿数据,userInfo的audittask+1
                      wx.cloud.callFunction({ //调用云函数获取openid
                        name: "getOpenId",
                        complete: res => {
                          db.collection("userInfo").where({
                            _openid: res.result.openid //进行筛选
                          }).get({

                            success: res => {
                              console.log("该用户的_id为：", res.data[0]._id)
                              db.collection('userInfo').doc(res.data[0]._id).update({
                                data: {
                                  audittask: _.inc(+1)
                                }
                              })
                              console.log("更新成功，待审核志愿+1")
                            },
                            fail: res => {
                              console.log("获取用户_id信息失败", res)
                            }
                          })
                        }
                      });

                    //增加该用户志愿报名记录 status表示状态，0：待审核，1：通过，2：未通过
                    db.collection("myTaskList").add({
                      data: {
                        realName:this.data.userInfo.realName,
                        userID:this.data.userInfo.userID,
                        title:this.data.detail.title,
                        startDate:this.data.detail.startDate,
                        location:this.data.detail.location.name,
                        status:0
                      },
                      success: res => {
                        console.log("报名记录添加成功", res)
                      }

                    })
                    this.setData({
                      confirm: true

                    })
                    console.log("该用户已报过名", this.data.confirm)


                  } else {
                    console.log('点击取消回调')
                  }
                }
              })
          } else {
            console.log("num=0，不允许报名", res.data.num)
            wx.showToast({
              title: '报名已结束',
            })
          }
        }
      })
    }








  }



})